<template>
  <div ref="chartEl" class="chart-container"></div>
</template>

<script setup>
import * as echarts from "echarts";
import { ref, onMounted, onBeforeUnmount, nextTick, defineProps } from "vue";
import { useResizeHandler } from "./components/useResizeHandler";

const chartEl = ref(null);
const chartInstance = ref(null);

// const getChartInstance = () => chartInstance.value;
const props = defineProps({
  msgData: {
    type: Object,
    default: () => {},
  },
});

// 初始化图表
const initChart = () => {
  if (chartEl.value) {
    chartInstance.value = echarts.init(chartEl.value);

    const option = {
      title: {
        text: props.msgData.title,
      },
      tooltip: {},
      xAxis: {
        data: props.msgData.txtKey,
      },
      yAxis: {},
      series: [
        {
          name: "金额",
          type: "bar",
          data: props.msgData.txtValue,
          barWidth: "30%", // 设置柱子宽度为30%
        },
      ],
    };

    chartInstance.value.setOption(option);
  }
};

// 自动监听 resize 和 sidebar 宽度变化
// useResizeHandler(getChartInstance);

onMounted(() => {
  nextTick(() => {
    initChart();
  });
  useResizeHandler(() => chartInstance.value);
});

onBeforeUnmount(() => chartInstance.value?.dispose());
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 400px;
  position: relative;
}
</style>
